<?php
namespace model;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use model\Query;


class SocketComunication implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);
        $conn->send($conn->resourceId);
        echo "New connection! ({$conn->resourceId})\n";
        return "returnvam";
        
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
      /*   echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); */
        
	//	$message = json_decode($msg);
	//	echo "message: " . var_dump(json_decode($msg, true)) . "\n";
	
        $json = json_encode($msg); 
        $jsonDecoded = json_decode($msg,true); 
        if (isset($jsonDecoded['type']))  {
       			if ($jsonDecoded['type'] == "teritory") {
        		$msgSent = $jsonDecoded['area'];
        		$t = $msgSent[4];
        		Query::updateTeritory(1, $msg , 2);
        }
        }
 
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
                
            }
        }
      
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}